package com.wdhcr.service.imp;


import com.wdhcr.entity.Tag;
import com.wdhcr.repository.TagRepository;
import com.wdhcr.service.TagService;
import javassist.NotFoundException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TagServiceImpl implements TagService {


    @Autowired
    private TagRepository tagRepository;


    @Override
    public Tag saveTag(Tag tag) {
        return tagRepository.save(tag);
    }

    @Override
    public Tag getTag(Long id) {
        return tagRepository.findById(id).get();
    }

    @Override
    public List<Tag> listTag() {
        return tagRepository.findAll();
    }


    @Override
    public Tag getTagByName(String name) {
        return tagRepository.findByName(name);
    }

    @Override
    public List<Tag> listTagTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(0, size, sort);
        return tagRepository.findAll(pageable).toList();
    }


    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagRepository.findAll(pageable);
    }



    @Override
    public Tag updateTag(Long id, Tag tag) throws NotFoundException {
        Tag tag1 = tagRepository.getOne(id);
        if (tag1 == null){
            throw  new NotFoundException("你所查询的标签不存在！！");
        }
        //把要更新的内容copy到查询出来的对象中
        BeanUtils.copyProperties(tag,tag1);
        return tagRepository.save(tag1);
    }

    @Override
    public void delete(Long id) {

        tagRepository.deleteById(id);

    }
}
